﻿using System;
using System.Collections.Generic;
using Devart.Data.SQLite;
using System.Data;
using JMI_Nucleo.Enumerador;

namespace JMI_Nucleo.Classe
{
    public class LogLocalDao : ILogLocal
    {
        private mLog infoLog;

        public LogLocalDao()
        {

        }

        #region Comandos SQL
        const string cmdSelect = "SELECT * FROM log ";
        const string cmdFiltroTipo = " WHERE TIPO =@TIPO ";
        const string cmdFiltroData = " WHERE DATAHORA BETWEEN @DATAINICIO AND @DATAFINAL ";
        const string cmdOderBy = "ORDER BY DataHora";
        #endregion

        #region Metodos Publicos
        List<mLog> ILogLocal.GetListaLog(SQLiteConnection Conexao, DateTime DataInicio, DateTime DataFinal)
        {
            List<mLog> lst = new List<mLog>();
            SQLiteDataReader rd = null;
            SQLiteCommand _cmd = null;
            SQLiteParameter p = null;
            
            string cmdSQL;
    
            try
            {
                _cmd = new SQLiteCommand();
                _cmd.Connection = Conexao;
                _cmd.CommandType = CommandType.Text;
                cmdSQL = cmdSelect + cmdFiltroData + cmdOderBy;
                _cmd.CommandText = cmdSQL;

                p = new SQLiteParameter();
                p.ParameterName = "@DATAINICIO";
                p.Value = DataInicio;
                _cmd.Parameters.Add(p);

                p = new SQLiteParameter();
                p.ParameterName = "@DATAFINAL";
                p.Value = DataFinal;
                _cmd.Parameters.Add(p);

                rd = _cmd.ExecuteReader();

                while (rd.Read())
                {
                    lst.Add(GetRd(rd));
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Erro ao executar comando. " + ex.Message);
            }
            finally
            {
                rd.Close();
            }
            return lst;
        }

        List<mLog> ILogLocal.GetListaLog(SQLiteConnection Conexao, TipoErro Tipo)
        {
            return null;
        }

        List<mLog> ILogLocal.GetListaLog(SQLiteConnection Conexao, TipoErro Tipo, DateTime DataInicio, DateTime DataFinal)
        {
            return null;
        }
        #endregion

        #region Metodos privados
        private mLog GetRd(SQLiteDataReader rd)
        {
            infoLog = new mLog();

            infoLog._TipoErro = (TipoErro)Enum.Parse(typeof(TipoErro), rd["TIPO"].ToString());
            infoLog.DataHora = Convert.ToDateTime(rd["DATAHORA"]);
            infoLog.Mensagem = rd["MENSAGEM"].ToString();
            infoLog.Metodo = rd["METODO"].ToString();
            infoLog.StackTrace = rd["STACKTRACE"].ToString();
            infoLog.Tabela = rd["TABELA"].ToString();

            return infoLog;
        }
        #endregion
    }
}
